<?php
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Config;

class WeixinHelper
{
	/**
	 * 获取access token
	 * @return string
	 */
	public function getAccessToken()
	{
		$key = 'WX_ACCESS_TOKEN';
		if (Cache::has($key)) {
			return Cache::get($key);
		} else {
			$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . Config::get('interface.weixin.APPID') . "&secret=" . Config::get('interface.weixin.SECRET');
			$accessTokenResult = file_get_contents($url);
			$accessTokenInfo = json_decode($accessTokenResult);
			$expiresAt = Carbon::now()->addSeconds($accessTokenInfo->expires_in);
			Cache::put($key, $accessTokenInfo->access_token, $expiresAt);

			return $accessTokenInfo->access_token;
		}
	}

	/**
	 * 通过code换取网页授权access_token
	 * @param string $code
	 * @return array
	 * {
	 * "access_token":"ACCESS_TOKEN",
	 * "expires_in":7200,
	 * "refresh_token":"REFRESH_TOKEN",
	 * "openid":"OPENID",
	 * "scope":"SCOPE",
	 * "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
	 * }
	 */
	public function oAuth($code)
	{
		$key = 'OAUTH_ACCESS_TOKEN-' . $code;
		$refesh_key = 'OAUTH_REFRESH_TOKEN-' . $code;
		if (Cache::has($key)) {
			return Cache::get($key);
		} elseif (Cache::has($refesh_key)) {
			$refresh_token = Cache::put($refesh_key);
			$url = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=" . Config::get('interface.weixin.APPID') . "&grant_type=refresh_token&refresh_token=" . $refresh_token;
		} else {
			$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . Config::get('interface.weixin.APPID') . "&secret=" . Config::get('interface.weixin.SECRET') . "&code=" . $code . "&grant_type=authorization_code";
		}

		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		//curl_setopt($ch, CURLOPT_COOKIEFILE,$this->cookieFile);
		curl_setopt($ch, CURLOPT_REFERER, $url);
		curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:20.0) Gecko/20100101 Firefox/20.0');
		$html = curl_exec($ch);
		curl_close($ch);
		$accessInfo = json_decode($html);

		$this->accessTokenType = 'OAUTH';
		Cache::put($key,$accessInfo,Carbon::now()->addSeconds($accessInfo->expires_in));
		Cache::put($refesh_key, $accessInfo->refresh_token, Carbon::now()->addDays(7));

		return $accessInfo;
	}

	public function getUserInfo($oath_access_token, $openid)
	{
		if ($this->accessTokenType == 'OAUTH') {
			$userUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $oath_access_token . "&openid=" . $openid;
		} else {
			if ($this->accessTokenType == 'GLOBAL') {
				$userUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" . $oath_access_token . "&openid=" . $openid;
			}
		}

		$ch = curl_init($userUrl);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		//curl_setopt($ch, CURLOPT_COOKIEFILE,$this->cookieFile);
		//curl_setopt($ch,CURLOPT_REFERER,$url);
		curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:20.0) Gecko/20100101 Firefox/20.0');
		$userInfo = curl_exec($ch);
		curl_close($ch);
		$userInfoArray = json_decode($userInfo);

		return $userInfoArray;
	}

	/**
	 * 获取公众号用于调用微信JS接口的临时票据
	 * @return Object 返回接口调用凭证信息
	 * {
	 * errcode:0,
	 * errmsg:"ok",
	 * ticket:"bxLdikRXVbTPdHSM05e5u5sUoXNKd8-41ZO3MhKoyN5OfkWITDGgnr2fwJ0m9E8NYzWKVZvdVtaUgWvsdshFKA",
	 * expires_in:7200
	 * }
	 */
	public function getJsapiTicket($access_token)
	{
		$key = 'WX_JSAPI_TICKET-' . $access_token;
		if (Cache::has($key)) {
			return Cache::get($key);
		}
		$url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={$access_token}&type=jsapi";
		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_REFERER, $url);
		curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:20.0) Gecko/20100101 Firefox/20.0');
		$html = curl_exec($ch);
		curl_close($ch);
		$ticketInfo = json_decode($html);

		$expiresAt = Carbon::now()->addSeconds($ticketInfo->expires_in);
		Cache::put($key, $ticketInfo->ticket, $expiresAt);

		return $ticketInfo->ticket;
	}

	/**
	 * 获取签名
	 * @param string $noncestr 随机字符串
	 * @param string $jsapi_ticket
	 * @param integer $timestamp
	 * @param string $url
	 * @return string
	 */
	public function getSignature($noncestr, $jsapi_ticket, $timestamp, $url)
	{
		$str = "jsapi_ticket=$jsapi_ticket&noncestr=$noncestr&timestamp=$timestamp&url=$url";
		$signature = sha1($str);

		return $signature;
	}

	/**
	 * 将指定的URL地址转换为微信授权自动登陆的地址
	 * （如果用户已经进行微信绑定，访问该方法转换的地址无需进行登录）
	 * @param string $url 需要转换的URL地址
	 * @return string 返回转换后的地址
	 */
	public function getUrl($url = '')
	{
		$base_wx_url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . WxPayConfig::APPID . "&redirect_uri=%s&response_type=code&scope=snsapi_base&state=1#wechat_redirect";

		if ($url == '') {
			return sprintf($base_wx_url, urlencode(Config::get('app.url') . Config::get('interface.weixin.REDIRECT_URI')));
		} else {
			return sprintf($base_wx_url, urlencode(Config::get('app.url') . Config::get("interface.weixin.REDIRECT_URI") . '?url=' . urlencode($url)));
		}
	}

	/**
	 * 删除菜单
	 * @return array
	 */
	public function deleteMenu()
	{
		$access_token = $this->getAccessToken();
		if ($access_token) {

			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token={$access_token}");
			curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
			curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:20.0) Gecko/20100101 Firefox/20.0');
			curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
			curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			$tmpInfo = curl_exec($ch);
			if (curl_errno($ch)) {
				echo 'Errno' . curl_error($ch);
			}
			curl_close($ch);

			return true;
		} else {
			return false;
		}
	}

	/**
	 * 创建菜单
	 * @param array $menuConfig
	 */
	public function createMenu($menuConfig)
	{
		$access_token = $this->getAccessToken();
		$data = json_encode($menuConfig);
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, "https://api.weixin.qq.com/cgi-bin/menu/create?access_token={$access_token}");
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
		curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:20.0) Gecko/20100101 Firefox/20.0');
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
		curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$tmpInfo = curl_exec($ch);
		if (curl_errno($ch)) {
			echo 'Errno' . curl_error($ch);
		}
		curl_close($ch);

	}

	/**
	 * 发送消息
	 * @param string $toUserName 接收方帐号（收到的OpenID）
	 * @param string $templateId 消息模板ID
	 * @param string $url 点击消息体进入的链接地址
	 * @param string $data 消息体
	 * @return mixed
	 */
	public function sendMessage($toUserName, $templateID, $url, $data)
	{
		//组建消息体
		$msgBody = [
			'touser'      => $toUserName,
			'template_id' => $templateID,
			'url'         => $url,
			'topcolor'    => '#FFFFFF',
			'data'        => $data,
		];

		$jsonData = json_encode($msgBody);

		$access_token = $this->getAccessToken();
		$url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $access_token;

		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);

		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);

		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

		$html = curl_exec($ch);
		curl_close($ch);

		$rs = json_decode($html);

		return $rs;
	}

	/**
	 * 统一回复封装
	 * @param $wx_openid
	 * @param $title
	 * @param $content
	 * @param string $url
	 * @return mixed
	 */
	public static function send_unified($wx_openid, $title, $content, $url = '')
	{
		$template_id = Config::get("interface.weixin.USER_QUESTION_NOTICE");
		$content = mb_substr($content, 0, 100, 'utf-8');
		$data = [
			'first'    => ['value' => sprintf("咨询主题：%s", $title), 'color' => '#000'],
			'keyword2' => ['value' => date("Y-m-d H:i:s"), 'color' => '#000'],
			'keyword3' => ['value' => $content, 'color' => '#000'],
			'remark'   => ['value' => "\n点击进行回复", 'color' => '#333'],
		];

		$url = Config::get('app.wechat_web_url') . $url;
		$wx = new self;
		$result = $wx->sendMessage($wx_openid, $template_id, $url, $data);
		return $result;
		//Log::info(json_encode($result));
	}

}